import java.util.HashMap;
import java.util.Map;

public class Codec {
    Map<String, String> map = new HashMap();
    int i = 0;

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        // 大体思路：给所有需要缩短的URL赋予一个字母+数字的组合可以让他们在hashmap中能够被辨认出来
        String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String key = "";
        // 根据自增变量，不断地获取charSet，形成字母+数字的组合
        while(i >= 0){
            int x = i % charSet.length();
            key = charSet.charAt(x) + key;
            i /= charSet.length();
            i--;
        }
        map.put(key, longUrl);
        return "http://tinyurl.com/" + key;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        // 根据缩短的URL缀截取字母+数字的组合，在hashmap中查找原始的URL
        String key = shortUrl.replaceAll("http://tinyurl.com/", "");
        return map.get(key);
    }

    public static void main(String[] args) {
        Codec codec = new Codec();
        String encode = codec.encode("https://leetcode.com/probles/design-tinyurl");
        System.out.println(encode);
        String decode = codec.decode(encode);
        System.out.println(decode);
    }
}
